package net.muchine.test.spring.data.example.core;

import java.net.UnknownHostException;

import net.muchine.test.spring.data.example.test.Tester;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import com.mongodb.Mongo;
import com.mongodb.MongoOptions;

@Configuration
public class MongoConfigApp {
	private static final Log log = LogFactory.getLog(MongoConfigApp.class);
	private String host = "localhost";
	private String database = "spring";

	@Bean
	public Mongo getMongo() throws UnknownHostException {
		MongoOptions options = new MongoOptions();
		options.setAutoConnectRetry(false);
		options.setConnectTimeout(5000);
		options.setSocketTimeout(5000);
		
		return new Mongo(this.host);
	}
	
	@Bean
	public MongoDbFactory getMongoDbFactory() throws UnknownHostException {
		return new SimpleMongoDbFactory(new Mongo(), database);
	}
	
	@Bean
	public MongoTemplate getMongoTemplate() throws UnknownHostException {
		return new MongoTemplate(this.getMongoDbFactory());
	}
	
	public static void main(String[] args) {
		ApplicationContext context = new AnnotationConfigApplicationContext(MongoConfigApp.class);
		log.info("context: " + context);
		
		MongoOperations mongo = new MongoTemplate(context.getBean(Mongo.class), "spring");
		
		Tester tester = new Tester(mongo);
		tester.test();
	}
}
